# db/mysql/dao/users.py
from typing import List, Optional
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from db.mysql.users import Users
from core.database import SessionLocal
import logging

logger = logging.getLogger(__name__)


class UsersDAO:
    def __init__(self, db: Session = None):
        self.db = db or SessionLocal()

    def create_user(self, user_data: dict) ->\
            Optional[Users]:
        """
        创建新用户

        Args:
            user_data: 用户数据字典

        Returns:
            Users: 创建的用户对象或 None
        """
        try:
            db_user = Users(**user_data)
            self.db.add(db_user)
            self.db.commit()
            self.db.refresh(db_user)
            logger.info(f"用户创建成功: {db_user.username}")
            return db_user
        except SQLAlchemyError as e:
            self.db.rollback()
            logger.error(f"创建用户失败: {str(e)}")
            return None

    def get_user_by_id(self, user_id: int) -> Optional[Users]:
        """
        根据ID获取用户

        Args:
            user_id: 用户ID

        Returns:
            Users: 用户对象或 None
        """
        try:
            return self.db.query(Users).filter(Users.id == user_id).first()
        except SQLAlchemyError as e:
            logger.error(f"查询用户失败 (ID: {user_id}): {str(e)}")
            return None

    def get_user_by_username(self, username: str) -> Optional[Users]:
        """
        根据用户名获取用户

        Args:
            username: 用户名

        Returns:
            Users: 用户对象或 None
        """
        try:
            return self.db.query(Users).filter(Users.username == username).first()
        except SQLAlchemyError as e:
            logger.error(f"查询用户失败 (用户名: {username}): {str(e)}")
            return None

    def get_user_by_email(self, email: str) -> Optional[Users]:
        """
        根据邮箱获取用户

        Args:
            email: 邮箱地址

        Returns:
            Users: 用户对象或 None
        """
        try:
            return self.db.query(Users).filter(Users.email == email).first()
        except SQLAlchemyError as e:
            logger.error(f"查询用户失败 (邮箱: {email}): {str(e)}")
            return None

    def get_user_by_user_id(self, user_id: str) -> Optional[Users]:
        """
        根据user_id获取用户

        Args:
            user_id: 用户唯一标识符

        Returns:
            Users: 用户对象或 None
        """
        try:
            return self.db.query(Users).filter(Users.user_id == user_id).first()
        except SQLAlchemyError as e:
            logger.error(f"查询用户失败 (user_id: {user_id}): {str(e)}")
            return None

    def get_all_users(self, skip: int = 0, limit: int = 100) -> List[Users]:
        """
        获取所有用户（分页）

        Args:
            skip: 跳过记录数
            limit: 限制记录数

        Returns:
            List[Users]: 用户列表
        """
        try:
            return self.db.query(Users).offset(skip).limit(limit).all()
        except SQLAlchemyError as e:
            logger.error(f"查询用户列表失败: {str(e)}")
            return []

    def update_user(self, user_id: int, user_data: dict) -> Optional[Users]:
        """
        更新用户信息

        Args:
            user_id: 用户ID
            user_data: 要更新的用户数据

        Returns:
            Users: 更新后的用户对象或 None
        """
        try:
            db_user = self.get_user_by_id(user_id)
            if db_user:
                for key, value in user_data.items():
                    setattr(db_user, key, value)
                self.db.commit()
                self.db.refresh(db_user)
                logger.info(f"用户更新成功: {db_user.username}")
                return db_user
            return None
        except SQLAlchemyError as e:
            self.db.rollback()
            logger.error(f"更新用户失败 (ID: {user_id}): {str(e)}")
            return None

    def delete_user(self, user_id: int) -> bool:
        """
        删除用户

        Args:
            user_id: 用户ID

        Returns:
            bool: 删除是否成功
        """
        try:
            db_user = self.get_user_by_id(user_id)
            if db_user:
                self.db.delete(db_user)
                self.db.commit()
                logger.info(f"用户删除成功: ID {user_id}")
                return True
            return False
        except SQLAlchemyError as e:
            self.db.rollback()
            logger.error(f"删除用户失败 (ID: {user_id}): {str(e)}")
            return False

    def authenticate_user(self, username: str, password: str) -> Optional[Users]:
        """
        用户认证

        Args:
            username: 用户名
            password: 密码（明文）

        Returns:
            Users: 认证成功的用户对象或 None
        """
        try:
            user = self.get_user_by_username(username)
            # 注意：实际应用中需要使用密码哈希验证
            # 这里仅为示例，实际应使用 passlib 等库进行密码验证
            if user and user.hashed_password == password:  # 仅作示例
                return user
            return None
        except Exception as e:
            logger.error(f"用户认证失败 (用户名: {username}): {str(e)}")
            return None

    def get_active_users(self, skip: int = 0, limit: int = 100) -> List[Users]:
        """
        获取活跃用户列表

        Args:
            skip: 跳过记录数
            limit: 限制记录数

        Returns:
            List[Users]: 活跃用户列表
        """
        try:
            return self.db.query(Users).filter(Users.is_active == True).offset(skip).limit(limit).all()
        except SQLAlchemyError as e:
            logger.error(f"查询活跃用户列表失败: {str(e)}")
            return []

    def close(self):
        """
        关闭数据库会话
        """
        self.db.close()


# 使用示例
def get_users_dao():
    """
    获取 UsersDAO 实例的依赖项
    """
    dao = UsersDAO()
    try:
        yield dao
    finally:
        dao.close()
